﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithm.Middle_16_reeSumClosest
{
    class MainProject
    {
        static void Main(string[] args)
        {
            int s = reeSumClosest(new int[] { 0,0,0 }, 1);
            Console.WriteLine(s);

            Console.ReadKey();
        }
        public static int reeSumClosest(int[] nums, int target)
        {
            //排序+双指针
            Array.Sort(nums);

            int firstIndex = 1;
            int secondIndex = nums.Length-1;

            int sum = 0;
            int res = 0;
            int min = int.MaxValue;
            for (int i = 0; i < nums.Length; i++)
            {
                firstIndex = i + 1;
                secondIndex = nums.Length - 1;
                while (firstIndex < secondIndex)
                {
                    sum = nums[i] + nums[firstIndex] + nums[secondIndex];

                    int temp = target - sum;

                    if (temp > 0)
                    {
                        firstIndex++;
                    }
                    else if (temp < 0)
                    {
                        secondIndex--;
                    }
                    else
                    {
                        return target;
                    }
                    int absValue = Math.Abs(temp);

                    if (absValue < min)
                    {
                        min = absValue;
                        res = sum;
                    }
                }
            }
            return res;
        }
    }
}
